#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/wait.h>
int main()
{
    int fds[2] = {0};
    int n = pipe(fds);
    if(n!=0)
    {
        std::cout<<"piep error"<<std::endl;
        return 1;
    }
    // father -> read
    // child --> write
    pid_t pid  = fork();
    if(pid>0)
    {
        //child
        //3.关闭read
        close(fds[0]);
        int cnt = 0;
        int total = 0;
        while(true)
        {
            std::string message = "h";
            total+= ::write(fds[1],message.c_str(),message.size());
            cnt++;
            cout<<"total:"<<total<<std::endl;
            sleep(2);
        }
        exit(1);
    }
    else
    {
        close(fds[1]);
        char buffer[1024];
        while(true)
        {
            sleep(1);
            size_t n = ::read(fds[0],buffer,1024);
            if(n>0)
            {
                buffer[n] = 0;
                std::cout<<"child->father,message:"<<buffer<<std::endl;

            }
            else if(n==0)
            {
                //写端口关闭
                std::cout<<"n:"<<n<<std::endl;
                std::cout<<"child quit??? me too"<<std::endl;
                break;
            }
        }
        //close(fds[0]);

    }
    int status = 0;
    pid_t rid = waitpid(pid,&status,0);
    std::cout<<"father wait child success:"<<rid<<"exit code:"<<((status>>8)&0xff)<<",exit sig:"<<
    (status&0x7f)<<std::endl;

}